package org.jeecg.chase.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Encoder;


import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class WeChatUtils {
  /**
    * 接口调用凭证 access_token
    */
  public static String postToken(String appId, String appKey) throws Exception {
         String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appKey;
        URL url = new URL(requestUrl);
         // 打开和URL之间的连接
         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
         connection.setRequestMethod("POST");// 设置通用的请求属性
         connection.setRequestProperty("Content-Type", "application/json");
         connection.setRequestProperty("Connection", "Keep-Alive");
         connection.setUseCaches(false);
         connection.setDoOutput(true);
         connection.setDoInput(true);
         // 得到请求的输出流对象
         DataOutputStream out = new DataOutputStream(connection.getOutputStream());
         out.writeBytes("");
         out.flush();
         out.close();
         // 建立实际的连接
         connection.connect();
         // 定义 BufferedReader输入流来读取URL的响应
         BufferedReader in;
         if(requestUrl.contains("nlp")){
             in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));

         } else{
             in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
         }
         StringBuilder result = new StringBuilder();
         String getLine;
         while ((getLine = in.readLine()) != null) {
                 result.append(getLine);
         }
         in.close();
         JSONObject jsonObject = JSONObject.parseObject(result.toString());
         return jsonObject.getString("access_token");
     }

           /**
             * 生成微信小程序二维码
            *
             * @param page
             *         当前小程序相对页面 必须是已经发布的小程序存在的页面(否则报错)，例如 pages/index/index, 根路径前不要填加 /,不能携带参数(参数请放在scene字段里)，如果不填写这个字段，默认跳主页面
             * @param scene
             *         最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，其它字符请自行编码为合法字符(因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式)
             * @param accessToken
             *         接口调用凭证
             */
  public static String generateQrCode(String page, String scene, String accessToken,String fileUrl) {
      ByteArrayOutputStream data = new ByteArrayOutputStream();
     try {
             //调用微信接口生成二维码
             URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
             HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
             httpURLConnection.setRequestMethod("POST");// 提交模式
             // conn.setConnectTimeout(10000);//连接超时 单位毫秒
             // conn.setReadTimeout(2000);//读取超时 单位毫秒
             // 发送POST请求必须设置如下两行
             httpURLConnection.setDoOutput(true);
             httpURLConnection.setDoInput(true);
             // 获取URLConnection对象对应的输出流
             PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
             // 发送请求参数
             JSONObject paramJson = new JSONObject();
             //这就是你二维码里携带的参数 String型  名称不可变
             paramJson.put("scene", scene);
             //注意该接口传入的是page而不是path
             paramJson.put("page", page);
             //这是设置扫描二维码后跳转的页面
             paramJson.put("width", 430);
             paramJson.put("is_hyaline", true);
             paramJson.put("auto_color", true);
             printWriter.write(paramJson.toString());
             // flush输出流的缓冲
             printWriter.flush();
             //开始获取数据
            if(StringUtils.isNotBlank(fileUrl)) {
                BufferedImage buffImg1 = ImageIO.read(new URL(fileUrl));
                    // 图片宽度
                double width = buffImg1.getWidth();
                    // 图片高度
                double height = buffImg1.getHeight();
                    //设置大小
                if (width > 188 && height > 188) {
                    width = 188/(double)buffImg1.getWidth()*(double)buffImg1.getWidth();
                    height = 188/(double)buffImg1.getHeight()*(double)buffImg1.getHeight();
                }
                BufferedImage tag = toBufferedImage(buffImg1.getScaledInstance((int)width, (int)height, Image.SCALE_DEFAULT));
                BufferedImage resultImg = null;
                    // 图片转圆形 --------stat
                    resultImg = new BufferedImage(tag.getWidth(), tag.getHeight(), BufferedImage.TYPE_INT_RGB);
                    Graphics2D g = resultImg.createGraphics();
//                    g.drawImage(tag.getScaledInstance((int)width,(int)height,Image.SCALE_SMOOTH),0,0,null);
                    Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, tag.getWidth(), tag.getHeight());
                    // 使用 setRenderingHint 设置抗锯齿
                    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                    resultImg = g.getDeviceConfiguration().createCompatibleImage(tag.getWidth(),tag.getHeight(),Transparency.TRANSLUCENT);
                    g = resultImg.createGraphics();
                    // 使用 setRenderingHint 设置抗锯齿
                    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                    g.setClip(shape);
                    g.drawImage(tag, 0, 0, null);
                    g.dispose();
                    byte[]  dataImg = changLogo(httpURLConnection.getInputStream(),resultImg);
                    data.write(dataImg);
            }else {
                BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
                int len = -1;
                byte[] arr = new byte[1024];
                while ((len = bis.read(arr)) != -1) {
                    data.write(arr, 0, len);
                }
                bis.close();
            }
         } catch (Exception e) {
             e.printStackTrace();
         }
      BASE64Encoder encoder = new BASE64Encoder();
      return  encoder.encode(data.toByteArray());
    }
    // image 转换成 BufferedImage
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }
        image = new ImageIcon(image).getImage();
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            int transparency = Transparency.OPAQUE;
            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {

        }

        if (bimage == null) {
            int type = BufferedImage.TYPE_INT_RGB;
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
        Graphics g = bimage.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        return bimage;
    }
    public static byte[] changLogo(InputStream in,BufferedImage logo) throws Exception {
        BufferedImage bdground1 = null;
        BufferedImage bdground = null;
        try {
            bdground1 = ImageIO.read(in);

            bdground= new BufferedImage(bdground1.getWidth(),bdground1.getHeight(),BufferedImage.TYPE_INT_RGB);
            bdground.getGraphics().drawImage(bdground1, 0, 0,bdground1.getWidth(), bdground1.getHeight(),Color.WHITE, null); // 绘制缩小后的图
            Graphics2D g = bdground.createGraphics();
            g.setBackground(Color.WHITE);//设置背景色
            g.drawImage(logo, 120, 120, 190, 190, null);
            g.dispose();
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            ImageIO.write(bdground, "jpg", result);
            result.flush();
            byte[] resultByte = result.toByteArray();
            return resultByte;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bdground != null) {
                bdground.getGraphics().dispose();
                bdground = null;
            }
            if (logo != null) {
                logo.getGraphics().dispose();
                logo = null;
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void getminiqrQr(String page, String scene, String accessToken) {
        try
        {
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene);
            paramJson.put("page", page);
            paramJson.put("width", 430);
            paramJson.put("auto_color", true);
            /**
             * line_color生效
             * paramJson.put("auto_color", false);
             * JSONObject lineColor = new JSONObject();
             * lineColor.put("r", 0);
             * lineColor.put("g", 0);
             * lineColor.put("b", 0);
             * paramJson.put("line_color", lineColor);
             * */

            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File("D:/1.png"));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1)
            {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        //获取接口调用凭证access_token
//        String appId = "wxf9f1558cf4214392";//小程序id
//        String appKey = "08dcacafc3542c8b3e176e5b9baf169e";//小程序密钥
//        String token = postToken(appId, appKey);
////        System.out.println(token);
////        getminiqrQr("aaaa",token);
//        getminiqrQr("pages/shopPage/shopPage","1513773996724219906" , token);
//        String base64String =  generateQrCode("pages/shopPage/shopPage","1513773996724219906" , token,"");
//        System.out.println(base64String);
//

//         System.out.println( fileName);
//        String url = "http://localhost:8080/adhadmin/sys/common/static/"+fileName;
//        URL url1 = new URL((url));
//        File file = new File(url);
//        BufferedImage bdground =  ImageIO.read(url1);
//        System.out.println(bdground.getWidth());
    }
}
